using LanqiQAwebapi.Models;
using LanqiQAwebapi.Interface;
using LanqiQAwebapi.Filter;
using LanqiQAwebapi.ConnectHubs;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using StackExchange.Redis;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using LanqiQAwebapi.Todo;
// ✅ 关键：导入包含 jwt 实现类的命名空间
using LanqiQAwebapi.ToolsHader;

namespace LanqiQAwebapi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // 配置 JSON 序列化
            builder.Services.AddControllers()
                .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
                });

            // 添加 Swagger/OpenAPI
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "LanqiQA API", Version = "v1" });

                // 添加 JWT Bearer 认证到 Swagger
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = @"JWT Authorization header using the Bearer scheme. Example: 'Bearer 12345abcdef'",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            },
                            Scheme = "oauth2"
                        },
                        new List<string>()
                    }
                });
            });

            // 配置数据库上下文
            builder.Services.AddDbContext<LanQiQaDBContext>(options =>
                options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

            // 配置 Redis
            var redisSection = builder.Configuration.GetSection("Redis:Default");
            string redisConnectionString = redisSection.GetSection("Connection").Value;

            // 注册 Redis 连接
            builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
            {
                return ConnectionMultiplexer.Connect(redisConnectionString);
            });

            // 注册自定义服务
            builder.Services.AddSingleton<ICacheService, CacheService>();
            builder.Services.AddScoped<IUserServer, UserServer>();
            builder.Services.AddScoped<Iessay, essay>();
            builder.Services.AddScoped<PreventDuplicateRequestsActionFilter>();

            // ✅ 关键：注册 Ijwt 服务 (假设实现类是 jwt)
            builder.Services.AddSingleton<Ijwt, jwt>();

            // 添加 SignalR
            builder.Services.AddSignalR();
            builder.Services.AddSingleton<IUserIdProvider, NameUserIdProvider>(); // 确保 NameUserIdProvider 已定义

            // JWT 认证配置
            builder.Services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["Jwt:Issuer"],
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["Jwt:Audience"],
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"])),
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero,
                    RequireExpirationTime = true
                };
            });

            // 配置 CORS
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("AllowCors", policy =>
                {
                    policy.AllowAnyOrigin()
                          .AllowAnyMethod()
                          .AllowAnyHeader();
                    // ⚠️ 生产环境务必修改为具体域名，例如：
                    // policy.WithOrigins("https://yourfrontend.com", "http://localhost:3000")
                    //       .AllowAnyHeader()
                    //       .AllowAnyMethod()
                    //       .AllowCredentials(); // 如果需要凭据
                });
            });

            var app = builder.Build();

            // 配置 HTTP 请求管道
          /*  if (app.Environment.IsDevelopment())
            {*/
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "LanqiQA API V1");
                });
           /* }*/
            // else
            // {
            //     // 生产环境考虑使用 HTTPS 重定向
            //     // app.UseHttpsRedirection();
            // }

            // ✅ 正确的中间件顺序 (至关重要)
            app.UseRouting();           // 1. 解析路由
            app.UseCors("AllowCors");   // 2. 处理跨域 (必须在认证前)
            app.UseAuthentication();    // 3. 身份认证
            app.UseAuthorization();     // 4. 授权检查

            // 映射控制器和 SignalR Hub
            app.MapControllers(); // 映射所有控制器的 API 路由
            app.MapHub<ConnectHub>("/connectHub"); // 映射 SignalR Hub

            app.Run(); // 启动应用
        }
    }
}